package com.ljkj.cordial.chat.activity;

import android.content.Intent;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanjiu.lib.business.FileTransmissionManager;
import com.lanjiu.lib.business.OriginalPictureVideoTransmissionCreator;
import com.lanjiu.lib.business.listener.FileTransmissionListener;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.log.Logger;
import com.lanjiu.lib.utils.th.Threader;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.PersonalView;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.widget.ProgressLayerView;
import com.nic.view.util.JToast;
import com.nic.view.util.glide.GlideUtil;
import com.nic.view.widget.ContainsEmojiEditText;
import com.yalantis.ucrop.UCrop;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.util.AlbumUtils;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 个人资料
 */
public class PersonalActivity extends AppEventActivity<PersonalView> {


    @BindView(R.id.iv_user)
    ImageView ivUser;
    @BindView(R.id.et_nickname)
    ContainsEmojiEditText etNickname;
    @BindView(R.id.et_phone)
    ContainsEmojiEditText etPhone;
    @BindView(R.id.ll_modify_password)
    LinearLayout llModifyPassword;
    @BindView(R.id.iv_modify_photo)
    ImageView ivModifyPhoto;
    @BindView(R.id.iv_nickname)
    ImageView ivNickname;
    @BindView(R.id.iv_phone)
    ImageView ivPhone;
    @BindView(R.id.iv_user_progress)
    ProgressLayerView plvUpload;
    @BindView(R.id.tv_log_off)
    TextView tvLogOff;

    /**
     * 缩略图路径
     */
    private String mPath;
    private UserTableBean u;
    private AlbumFile album;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_personal;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        getToolbar().setTitle("个人资料");
        getUserInfo();
    }


    private void getUserInfo() {
//        ObserverThread.create().onNextThread1()
        u = UserTableBean.getCurrentUser();
        if (u != null) {
            etNickname.setText(u.getNickname());
            etPhone.setText(u.getPhone());
            if (!TextUtils.isEmpty(u.getAvatar())) {
                AlbumManageUtil.getInstance().downLoadFileFriend(u.getAvatar(), u.getUserId(), ivUser);
            }
        }
    }

    @OnClick({R.id.iv_user, R.id.iv_modify_photo, R.id.ll_modify_password, R.id.et_nickname, R.id.et_phone, R.id.iv_nickname, R.id.iv_phone, R.id.tv_log_off})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_user:
//                if (TextUtils.isEmpty(mPath)) {
//                    ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<UserTableBean>() {
//                        @Override
//                        public void onAction(UserTableBean u) {
//                            if (u != null && !TextUtils.isEmpty(u.getAvatarId())) {
//                                AlbumTableBean bean = AlbumTableBean.queryById(Long.valueOf(u.getAvatarId()));
//                                if (bean != null && !TextUtils.isEmpty(bean.getMPath())) {
//                                    mPath = bean.getMPath();
//                                    AlbumManageUtil.getInstance().lookLargePhoto(PersonalActivity.this, mPath);
//                                    return;
//                                }
//                            }
//                            LookLargePhotoDialog dialog = new LookLargePhotoDialog(PersonalActivity.this);
//                            AlbumManageUtil.getInstance().downLoadFileFriend(u.getAvatar(), u.getUserId(), dialog.getImageView());
//                            dialog.show();
//                        }
//
//                        @Override
//                        public UserTableBean onThreadAction() {
//                            return UserTableBean.getCurrentUser();
//                        }
//                    });
//                } else {
//                    AlbumManageUtil
//                            .getInstance().lookLargePhoto(this, mPath);
//                }
            case R.id.iv_modify_photo:
                AlbumManageUtil
                        .getInstance().selectSingleImage(this, new AlbumManageUtil.OnAlbumResultListener() {
                    @Override
                    public void onResult(ArrayList<AlbumFile> albumFiles) {
                        album = albumFiles.get(0);
                        Uri sourceUri = Uri.fromFile(new File(album.getPath()));
                        ivModifyPhoto.post(new Runnable() {
                            @Override
                            public void run() {
                                UCrop.Options options = new UCrop.Options();
                                options.setStatusBarColor(ContextCompat.getColor(PersonalActivity.this, R.color.albumColorPrimary));
                                options.setToolbarColor(ContextCompat.getColor(PersonalActivity.this, R.color.albumColorPrimary));
                                options.setToolbarWidgetColor(ContextCompat.getColor(PersonalActivity.this, R.color.white));
                                options.setActiveControlsWidgetColor(ContextCompat.getColor(PersonalActivity.this, R.color.green2));
                                options.setActiveWidgetColor(ContextCompat.getColor(PersonalActivity.this, R.color.green2));
                                //裁剪
                                UCrop.of(sourceUri, sourceUri)
                                        .withOptions(options)
                                        .withAspectRatio(1, 1)//16:9
                                        .withMaxResultSize(480, 480)
                                        .start(PersonalActivity.this);
                            }
                        });

                    }

                    @Override
                    public void onCancel(String result) {

                    }
                });
                break;
            case R.id.ll_modify_password:
                ForgetPasswordActivity.jumpTo(this, Canstants.STATE_FIND_PASSWORD);
                break;
            case R.id.iv_nickname:
            case R.id.et_nickname:
                ModifyRemarkActivity.jumpTo(this, ModifyRemarkActivity.OPTION_NICK, "修改昵称", etNickname.getText().toString(), Canstants.KEY_REMARK_RESULT);
                break;
            case R.id.et_phone:
            case R.id.iv_phone:
                String phone = etPhone.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    ModifyPhoneActivity.jumpTo(this, Canstants.TYPE_ADD, null, Canstants.REQUEST_CODE_300);
                } else {
                    ModifyPhoneActivity.jumpTo(this, Canstants.TYPE_MODIFY, phone, Canstants.REQUEST_CODE_301);
                }
                break;
            case R.id.tv_log_off:
//                DeleteHistoryUtil.getInstance().deleteNavChat(ChatApp.getInstance().getUserId(),true,true);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
                final Uri resultUri = UCrop.getOutput(data);
                mPath = resultUri.getPath();
                FileTransmissionManager.getInstance().buildUploader()
                        .targetPath(mPath)
                        .onFileReceiver(new FileTransmissionListener.OnFileSenderListener() {
                            @Override
                            public void onStart() {
                                plvUpload.setVisibility(View.VISIBLE);
                                plvUpload.setProgress(0);
                            }

                            @Override
                            public void onProgress(int progress) {
                                plvUpload.setProgress(progress);
                            }

                            @Override
                            public void onComplete(String serverPath) {
                                dismissNet(isShowDefNetDialog());
                                Logger.print("serverPath" + serverPath);
                                plvUpload.setVisibility(View.INVISIBLE);
//                                obtainView().doModifyPhoto(serverPath);
//                ImageLoader.getInstance().displayLocalAvatar(u.getAvatarPath(), ivUser);
                                GlideUtil.getInstance().load(mPath, ivUser);
                                saveAvatar(serverPath, mPath);
                            }

                            @Override
                            public void onError(int code, String msg) {
                                dismissNet(isShowDefNetDialog());
                                plvUpload.setVisibility(View.INVISIBLE);
                                JToast.showShort(PersonalActivity.this, "上传失败");
                                if (TextUtils.isEmpty(mPath)) {
                                    ivUser.setImageResource(R.mipmap.pic_user_avatar_default_36dp);
                                }
                            }
                        })
                        .friend(OriginalPictureVideoTransmissionCreator.avatar(UserPreferences.isRegistered(), UserPreferences.getUserId()))
                        .upload();
                return;
            } else if (resultCode == UCrop.RESULT_ERROR) {
                final Throwable cropError = UCrop.getError(data);
                if (cropError != null)
                    cropError.printStackTrace();
                return;
            }
            if (Canstants.KEY_REMARK_RESULT == requestCode && Canstants.KEY_REMARK_RESULT == resultCode) {
                String remark = data.getStringExtra(Canstants.KEY_REMARK);
                etNickname.setText(remark);
                return;
            }
            if (resultCode == Canstants.RESULT_CODE_300) {
                String phone = data.getStringExtra(Canstants.KEY_TITLE);
                etPhone.setText(phone);
//                if (requestCode == Canstants.REQUEST_CODE_300) {
//                } else if (requestCode == Canstants.REQUEST_CODE_301) {
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void saveAvatar(String serverPath, String locPath) {
        Threader.run(() -> {
            UserTableBean u = UserTableBean.getCurrentUser();
            if (u != null && album != null) {
                if (!TextUtils.isEmpty(u.getAvatarPath())) {
                    AlbumManageUtil.deleteFile(u.getAvatarPath());
//                    AlbumTableBean oldFile = AlbumTableBean.queryById(Long.parseLong(u.getAvatarId()));
//                    if (oldFile != null) {
//                        deleteOldAvatar(oldFile.getMPath(), oldFile.getMThumbPath());
//                        AlbumTableBean.delete(Long.parseLong(u.getAvatarId()));
//                    }
                }
                if (this.album != null) {
//                    deleteOldAvatar(this.album.getPath());
                    AlbumManageUtil.deleteFile(this.album.getThumbPath());
                }
                String thumbPath = AlbumUtils.randomAvatarPath(ChatApp.getContext(), ChatApp.getContext().getPackageName(), ChatApp.getInstance().getUserId(), serverPath);
                AlbumFile album = AlbumManageUtil.getInstance().getAlbumFile(this, locPath, thumbPath);
//                Long ab = AlbumManageUtil.insertAlbumFileToTable(album, AlbumTableBean.TYPE_AVATAR);
                u.setAvatar(serverPath);
//                u.setAvatarId("" + ab);
                u.setAvatarPath(TextUtils.isEmpty(album.getThumbPath()) ? locPath : album.getThumbPath());
                UserTableBean.update(u);
            }

//            ChatTableBean.updateFriendAvatar(UserPreferences.getUserId(), serverPath);
        });
    }


    @Override
    protected PersonalView bindNettyMessageView() {
        return new PersonalView((code, msg, data) -> {
            if (code == IMSContacts.ResponseCode.SUCCESS) {
                if (null != data) {
                    saveAvatar(data.getAvatar(), mPath);
                }
            } else {
                JToast.showShort(PersonalActivity.this, msg);
                if (TextUtils.isEmpty(mPath)) {
                    ivUser.setImageResource(R.mipmap.pic_user_avatar_default_36dp);
                } else {
                    GlideUtil.getInstance().load(mPath, ivUser);
                }
            }
        });
    }

}
